<template>
    <div class="edit-task">
      <h2>编辑任务</h2>
      <el-form :model="task" label-width="80px" @submit.native.prevent="submitForm">
        <el-form-item label="名称">
          <el-input v-model="task.name" required></el-input>
        </el-form-item>
        <el-form-item label="完成状态">
          <el-select v-model="task.completed">
            <el-option :value="true" label="已完成"></el-option>
            <el-option :value="false" label="未完成"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        task: {
          id: null,
          name: '',
          completed: false
        }
      };
    },
    created() {
      // 获取任务ID
      const taskId = this.$route.params.taskId;
      // 根据任务ID获取任务信息
      this.fetchTask(taskId);
    },
    methods: {
      fetchTask(taskId) {
        const token = localStorage.getItem('token');
        axios
          .get(`/api/tasks/${taskId}`, {
            headers: {
              Authorization: token
            }
          })
          .then(response => {
            this.task = response.data;
          })
          .catch(error => {
            this.$message.error('获取任务信息失败');
          });
      },
      submitForm() {
        const token = localStorage.getItem('token');
        const taskId = this.task.id;
        const updatedTask = {
          name: this.task.name,
          completed: this.task.completed
        };
  
        axios
          .put(`/api/tasks/${taskId}`, updatedTask, {
            headers: {
              Authorization: token
            }
          })
          .then(response => {
            this.$message.success('任务编辑成功');
            this.$router.push('/todo_list');
          })
          .catch(error => {
            this.$message.error('任务编辑失败');
          });
      }
    }
  };
  </script>